/**
 * 
 */
package game;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;

/**
 * @author patrick
 * 
 */
public class MusicPlayer extends Thread {

	private Player player;

	private String filePath;
	private File track;
	private String [] trackList;
	private int currentTrack;
	private boolean stop;

	/**
	 * create a MusicPlayer and play default music
	 * */
	public MusicPlayer() {
		
		// WARNING: HARD CODED!!
		trackList = new String[3];
		trackList[0] = "src/music/ghosts6.mp3";
		trackList[1] = "src/music/corona radiata.mp3";
		trackList[2] = "src/music/the four of us are dying.mp3";

		currentTrack = 0;
		
		stop = false;

		start();
		startMusic();
	}

	/**
	 * restartes the player if track is done
	 * */
	public void run() {

		while (true) {
//			if(stop){
//				stopMusic();
//				return;
//			}
				
			if(player != null){
				if (player.isComplete()) {

					if(currentTrack < trackList.length-1)
						currentTrack++;
					else
						currentTrack = 0;
					startMusic();
					
				} else {
//					System.out.println("music is still playing!");
				}
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * start the track
	 * */
	public void startMusic() {
		
		track = new File(trackList[currentTrack]);
		
//		System.out.println("name of soundfile: " + track.getName());
		filePath = track.getAbsolutePath();

//		System.out.println("filepath=" + filePath);
		
		
		try {
			FileInputStream is = new FileInputStream(track);

			player = new Player(is);

			player.play();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (JavaLayerException e) {
			e.printStackTrace();
		}

	}

	/**
	 * stops the currently playing track
	 * */
	public void stopMusic() {
		 player.close();
	}

	/**
	 * @return the stop
	 */
	public boolean isStop() {
		return stop;
	}

	/**
	 * @param stop the stop to set
	 */
	public void setStop(boolean stop) {
		this.stop = stop;
	}


}
